<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //记录sql日志
        $this->_bindSqlQueryLog();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    }
    
    /**
     * sql日志
     */
    private function _bindSqlQueryLog() {
        if (env('SQL_DEBUG')) {
            DB::listen(function ($sql) {
                foreach ($sql->bindings as $i => $binding) {
                    if ($binding instanceof \DateTime) {
                        $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                    } else {
                        if (is_string($binding)) {
                            $sql->bindings[$i] = "'$binding'";
                        }
                    }
                }
                $query = str_replace(['%', '?'], ['%%', '%s'], $sql->sql);
                $path  = 'logs/sql/sql-' . date('Y-m-d', time()) . '.log';
                $log   = new Logger('sql');
                $log->pushHandler(new StreamHandler(storage_path($path), Logger::INFO));
                $log->addInfo(vsprintf($query, $sql->bindings) . ';  -- [耗时]：' . $sql->time . ' ms');
            });
        }
    }
}
